package services

import (
	"bubble-auth-test/database"
	"bubble-auth-test/models"
	"bubble-auth-test/utils"
	"errors"
	"golang.org/x/crypto/bcrypt"
)

// Authenticate1 method to validate user and generate JWT
func Authenticate1(username string, password string) (string, error) {
	var user models.User
	// 查找用户
	if err := database.DB.Where("username = ?", username).First(&user).Error; err != nil {
		return "", errors.New("user not found")
	}

	// 比对密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		return "", errors.New("invalid password")
	}

	// 生成JWT
	return utils.GenerateJWT(user.Username)
}

func Register(username, password string) error {
	// 检查用户名是否已存在
	var user models.User
	if err := database.DB.Where("username = ?", username).First(&user).Error; err == nil {
		return errors.New("username already exists")
	}

	// 加密密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		return errors.New("failed to hash password")
	}

	// 保存用户数据
	newUser := models.User{
		Username: username,
		Password: string(hashedPassword),
	}

	if err := database.DB.Create(&newUser).Error; err != nil {
		return errors.New("failed to create user")
	}

	return nil
}

func Authenticate(username string, password string) (string, error) {
	var user models.User
	// 查找用户
	if err := database.DB.Where("username = ?", username).First(&user).Error; err != nil {
		return "", errors.New("user not found")
	}

	// 比对密码
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		return "", errors.New("invalid password")
	}

	// 生成JWT
	return utils.GenerateJWT(user.Username)
}
